<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 确保用户已登录
if (!isset($_SESSION['username'])) {
    header('Location: welcome.php');
    exit();
}

// 用户目录路径
$user_dir = __DIR__ . '/user/';
$init_records_dir = __DIR__ . '/init_records/';
$init_records_file = $init_records_dir . 'records.txt';

// 确保用户目录存在
if (!file_exists($user_dir)) {
    mkdir($user_dir, 0755, true);
}

// 确保初始化记录目录存在
if (!file_exists($init_records_dir)) {
    mkdir($init_records_dir, 0755, true);
}

// 处理初始化表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_action'])) {
    // 获取当前用户名
    $username = $_SESSION['username'];
    
    // 检查用户是否存在于记录中
    $records = [];
    if (file_exists($init_records_file)) {
        $records = json_decode(file_get_contents($init_records_file), true) ?: [];
    }
    
    // 记录用户初始化状态
    $records[$username] = [
        'init_time' => time(),
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => substr($_SERVER['HTTP_USER_AGENT'], 0, 100)
    ];
    
    file_put_contents($init_records_file, json_encode($records), LOCK_EX);
    
    // 创建用户文件夹
    $user_folder = $user_dir . $username;
    if (!file_exists($user_folder)) {
        mkdir($user_folder, 0755);
    }
    
    // 根据用户选择跳转
    if ($_POST['user_action'] === 'skip') {
        header('Location: index.php');
        exit;
    } elseif ($_POST['user_action'] === 'setup') {
        header('Location: user_settings.php');
        exit;
    }
}

// 检查用户是否需要初始化
if (needInitialization()) {
    displayInitializationPage();
    exit; // 停止后续执行
}

/**
 * 检查用户是否需要初始化
 */
function needInitialization() {
    global $init_records_file;
    
    // 确保用户名存在
    if (!isset($_SESSION['username'])) return false;
    
    $username = $_SESSION['username'];
    
    // 如果记录文件不存在，说明用户未初始化
    if (!file_exists($init_records_file)) return true;
    
    // 检查记录文件
    $records = json_decode(file_get_contents($init_records_file), true);
    if ($records === null) return true; // 文件损坏，重新初始化
    
    // 检查该用户是否完成过初始化
    return !isset($records[$username]);
}

/**
 * 显示初始化页面
 */
function displayInitializationPage() {
    $username = htmlspecialchars($_SESSION['username']);
    $first_letter = strtoupper(substr($username, 0, 1));
    
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JIIL微聊 - 初始化账户</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }
            
            body {
                background-color: #ffffff;
                color: #000000;
                min-height: 100vh;
                display: flex;
                flex-direction: column;
            }
            
            /* 顶部导航栏 */
            .top-bar {
                background-color: #ffffff;
                height: 60px;
                padding: 0 20px;
                display: flex;
                align-items: center;
                border-bottom: 1px solid #f0f0f0;
                position: relative;
            }
            
            .top-bar h1 {
                font-size: 18px;
                font-weight: 600;
                color: #000000;
            }
            
            /* 返回按钮 */
            .back-btn {
                width: 36px;
                height: 36px;
                background: #000000;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                margin-right: 10px;
            }
            
            .back-btn::before {
                content: "";
                display: block;
                width: 10px;
                height: 10px;
                border-left: 2px solid white;
                border-bottom: 2px solid white;
                transform: rotate(45deg);
                margin-left: -2px;
            }
            
            /* 主内容区 */
            .init-container {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                flex: 1;
                padding: 20px;
                text-align: center;
            }
            
            .welcome-title {
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 20px;
                color: #333333;
                line-height: 1.4;
            }
            
            .description {
                font-size: 16px;
                color: #666666;
                line-height: 1.6;
                margin-bottom: 30px;
                max-width: 500px;
            }
            
            /* 按钮组样式 */
            .button-group {
                display: flex;
                gap: 15px;
                margin-top: 20px;
            }
            
            .btn {
                padding: 14px 30px;
                border-radius: 8px;
                font-size: 16px;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.3s ease;
                border: none;
                min-width: 150px;
            }
            
            .btn-skip {
                background-color: #ffffff;
                color: #666666;
                border: 1px solid #e0e0e0;
            }
            
            .btn-skip:hover {
                background-color: #f9f9f9;
            }
            
            .btn-setup {
                background-color: #000000;
                color: #ffffff;
            }
            
            .btn-setup:hover {
                background-color: #222222;
            }
            
            /* 用户信息展示 */
            .user-info {
                display: flex;
                align-items: center;
                background: #f9f9f9;
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            
            .avatar {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background-color: #e0e0e0;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 15px;
                color: #999;
                font-weight: bold;
                font-size: 20px;
            }
            
            .username {
                font-weight: 600;
                font-size: 18px;
            }
            
            /* 响应式设计 */
            @media (max-width: 480px) {
                .button-group {
                    flex-direction: column;
                    width: 100%;
                }
                
                .btn {
                    width: 100%;
                }
            }
        </style>
    </head>
    <body>
        <!-- 顶栏 -->
        <div class="top-bar">
            <div class="back-btn" onclick="history.back()"></div>
            <h1>初始化账户</h1>
        </div>
        
        <!-- 主内容区 -->
        <form method="post" class="init-container">
            <div class="user-info">
                <div class="avatar">
                    <?php echo $first_letter; ?>
                </div>
                <div class="username">
                    <?php echo $username; ?>
                </div>
            </div>
            
            <h2 class="welcome-title">欢迎您注册JIIL微聊账户</h2>
            <p class="description">
                首次使用前，您需要完成一些基本设置。这将帮助您更好地使用我们的服务。您也可以选择稍后在用户设置中配置。
            </p>
            
            <div class="button-group">
                <button type="submit" name="user_action" value="skip" class="btn btn-skip">跳过，稍后设置</button>
                <button type="submit" name="user_action" value="setup" class="btn btn-setup">前往设置</button>
            </div>
        </form>
    </body>
    </html>
    <?php
}